<?php

namespace App\Scope;

use App\Kuafu\Shop\Model\Shop;
use Closure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Collection;

class ShopScope implements Scope
{
    /**
     * @var string 关联方法名称
     */
    public string $relationName;

    /**
     * @var string|Closure 关联字段
     */
    public  $relationColumnName;

    /**
     * @var Closure where额外条件过滤
     */
    public Closure $extraWhere;

    /**
     * @var string 关联方法
     */
    public string $relationFunction;

    /**
     * @param mixed $relationColumnName
     * @param string $relationName
     * @param string $relationFunction
     * @param Closure|null $extraWhere
     */
    public function __construct(
         $relationColumnName = "shopId",
        string $relationName = "",
        string $relationFunction = "",
        Closure $extraWhere = null
    ) {
        $this->relationColumnName = $relationColumnName;
        $this->relationName       = $relationName;
        $this->relationFunction   = $relationFunction;
        $this->extraWhere         = $extraWhere ? $extraWhere : function (Builder $builder) {
            return $builder;
        };
    }

    public function apply(Builder $builder, Model $model)
    {
        // TODO: Implement apply() method.
        $shopIdsArr = self::getShopIdsArr();
        if ($shopIdsArr) {
            if ($this->relationName) {
                return (($this->extraWhere)($builder))
                    ->{$this->relationFunction}(
                        $this->relationName,
                        function ($query) use ($shopIdsArr) {
                            return $query->whereIn($this->relationColumnName, $shopIdsArr);
                        });
            }

            if($this->relationColumnName instanceof Closure){
                return ($this->relationColumnName)($builder);
            }else{
                return $builder->whereIn($this->relationColumnName, $shopIdsArr);
            }
        }
        return $builder;
    }

    public static ?array $shopIds = null;

    public static function getShopIdsArr()
    {
        if(is_null(self::$shopIds)){
            $shopIds = app()->get("request")->get("shopIds", "");
            self::$shopIds = [];
            if($shopIds && $shopIdsArr = array_filter(explode(",", $shopIds))){
                self::$shopIds = $shopIdsArr;
            }
        }
        return self::$shopIds;
    }

    /**
     * @return Collection
     */
    public static function getShopsType(): Collection
    {
        return  Shop::query()
            ->whereIn('id', ShopScope::getShopIdsArr())
            ->get()
            ->pluck("type");
    }
}
